<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>图书信息管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../layuimini/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../layuimini/css/public.css" media="all">
    <script src="../layuimini/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script src="../layuimini/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
</head>
<body>
<!--编辑弹出框-->
<div class="site-text" style="margin: 5%; display: none" id="edit_window">
    <div class="layui-form" style="width: 400px; float: left" lay-filter="editForm">
        <!--隐藏域，id-->
        <input type="hidden" id="bookid" name="bookid" class="layui-input" value="null">
        <!--隐藏域，封面地址-->
        <input type="hidden" id="bookimg" name="bookimg" class="layui-input" value="null">
        <!--图书名-->
        <div class="layui-form-item">
            <label class="layui-form-label">图书名</label>
            <div class="layui-input-block">
                <input type="text" id="bookname" name="bookname" value="" placeholder="请输入图书名" class="layui-input">
            </div>
        </div>
        <!--作者-->
        <div class="layui-form-item">
            <label class="layui-form-label">作者</label>
            <div class="layui-input-block">
                <input type="text" id="bookauthor" name="bookauthor" value="" placeholder="请输入作者" class="layui-input">
            </div>
        </div>
        <!--价格-->
        <div class="layui-form-item">
            <label class="layui-form-label">价格</label>
            <div class="layui-input-block">
                <input type="text" id="bookprice" name="bookprice" value="" placeholder="请输入价格" class="layui-input">
            </div>
        </div>
        <!--图书类型-->
        <div class="layui-form-item">
            <label class="layui-form-label">图书类型</label>
            <div class="layui-input-block">
                <select name="booktypeid" id="edit_booktypeid" lay-search="">
                    <option value="">请选择所属类型</option>
                </select>
            </div>
        </div>
        <!--书籍描述-->
        <div class="layui-form-item">
            <label class="layui-form-label">书籍描述</label>
            <div class="layui-input-block">
                <textarea id="bookdesc" name="bookdesc" value="" placeholder="请输入描述" class="layui-textarea"></textarea>
            </div>
        </div>
        <!--是否是管理员-->
        <div class="layui-form-item">
            <label class="layui-form-label">是否被借出</label>
            <div class="layui-input-block">
                <input type="radio" name="isborrowed" value="1" title="是" checked="checked">
                <input type="radio" name="isborrowed" value="0" title="否">
            </div>
        </div>
    </div>
    <!--封面上传-->
    <div style="float:right;">
        <p>上传封面</p>
        <div style="margin-top: 20px"></div>
        <div class="layui-upload">
            <button type="button" class="layui-btn" id="test1">上传图片</button>
            <div class="layui-upload-list">
                <img width="200px" class="layui-upload-img" id="demo1" />
                <p id="demoText"></p>
            </div>
            <div style="width: 95px">
                <div class="layui-progress layui-progress-big"
                     lay-showpercent="yes"
                     lay-filter="demo">
                    <div class="layui-progress-bar" lay-percent=""></div>
                </div>
            </div>
        </div>
    </div>

</div>
<!--数据表格布局-->
<div class="layuimini-container">
    <div class="layuimini-main">
        <!--搜索栏-->
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" lay-filter="searchForm">
                    <div class="layui-form-item">
                        <!--搜索书名或作者-->
                        <div class="layui-inline">
                            <label class="layui-form-label">书名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="bookname" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">作者</label>
                            <div class="layui-input-inline">
                                <input type="text" name="bookauthor" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">所属类型</label>
                            <div class="layui-input-inline">
                                <select name="booktypeid" id="search_booktypeid" lay-search="">
                                    <option value="">请选择所属类型</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜　　索 </button>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-all-btn"><i class="layui-icon"></i> 显示全部 </button>
                        </div>
                    </div>
                </form>
                <p>搜索框支持模糊查询，某项不填则不作为查询条件。</p>
            </div>
        </fieldset>
        <!--头部工具栏-->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加一行 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除选中行 </button>
            </div>
        </script>
        <!--表格容器-->
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <!--行工具栏-->
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>
    </div>
</div>
<!--js代码-->
<script>
    layui.use(['form', 'table', 'upload', 'element'], function () {
        var $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                upload = layui.upload,
                element = layui.element;

        //上传图片
        var uploadInst = upload.render({
            elem: "#test1",
            url: "../update/updateImg",
            before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $("#demo1").attr("src", result); //图片链接（base64）
                });
                element.progress("demo", "0%"); //进度条复位
                layer.msg("上传中", { icon: 16, time: 0 });
            },
            done: function (res) {
                console.log(res);
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg("上传失败");
                }
                //上传成功的一些操作
                //把地址写到表单的隐藏域中
                $("#bookimg").val(res.data);
                //图片链接替换
                $("#demo1").attr("src", res.data);

                $("#demoText").html(""); //置空上传失败的状态
            },
            error: function () {
                //演示失败状态，并实现重传
                var demoText = $("#demoText");
                demoText.html(
                        '<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'
                );
                demoText.find(".demo-reload").on("click", function () {
                    uploadInst.upload();
                });
            },
            //进度条
            progress: function (n, elem, e) {
                element.progress("demo", n + "%"); //可配合 layui 进度条元素使用
                if (n == 100) {
                    layer.msg("上传完毕", { icon: 1 });
                }
            },
        });

        //获取所有的类型
        $.getJSON({
            url: '../bookType/queryBookTypes',
            success: function (data) {
                // $("#edit_booktypeid").html("");
                $.each(data,function (i,n) {
                    $("#edit_booktypeid")
                            .append("<option value=\""+n.booktypeid+"\">"+n.booktypename+"</option>")
                });
                form.render('select','editForm'); //刷新select选择框渲染

                // $("#search_booktypeid").html("");
                $.each(data,function (i,n) {
                    $("#search_booktypeid")
                            .append("<option value=\""+n.booktypeid+"\">"+n.booktypename+"</option>")
                });
                form.render('select','searchForm'); //刷新select选择框渲染
            }
        });

        //加载数据表格
        table.render({
            elem: '#currentTableId',
            url: '../bookInfo/queryBookInfosByPage',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {type: "checkbox"},
                {field: 'bookid', title: '序号', sort: true},
                {field: 'bookname', title: '书名', sort: true},
                {field: 'bookauthor', title: '作者', sort: true},
                {field: 'bookprice', title: '价格', sort: true},
                {field: 'booktypename', title: '类型名', sort: true},
                {field: 'bookdesc', title: '描述'},
                {field: 'isborrowed', title: '是否被借出', sort: true},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [5, 10, 15, 20, 25, 50, 100],
            limit: 10,
            page: {
                prev: '上一页',
                next: '下一页',
            },
            done: function (res) {
                console.log(res);
            },
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            console.log(result);
            //执行搜索重载
            table.reload('currentTableId', {
                url: '../bookInfo/searchBookInfosByPage',
                where: {json:result},   //把json传过去
                page: {curr: 1}, //重新从第 1 页开始
                done: function (res) {
                    layer.msg("搜索到"+res.count+"个结果", {time:800});
                    return res;
                }
            });
            return false;   //不跳转
        });

        // 监听显示全部操作
        form.on('submit(data-all-btn)', function (data) {
            form.val("searchForm", {
                'bookname':null,
                'bookauthor':null,
                'booktypeid':null
            });
            //执行搜索重载
            table.reload('currentTableId', {
                url: '../bookInfo/queryBookInfosByPage',
                page: {curr: 1}, //重新从第 1 页开始
                done: null
            });
            return false;   //不跳转
        });

        //toolbar监听事件
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                layer.open({
                    title:"新增",
                    type: 1,
                    maxmin:true,
                    shadeClose: true,
                    area:['800px','600px'],
                    btn: ['确定', '取消'],
                    content: $("#edit_window"),
                    success: function () {  //弹出框成功回调
                        //给表单赋值
                        form.val("editForm", {
                            "bookid": null,
                            "bookname": '红楼梦',
                            "bookauthor": '曹雪芹',
                            "bookprice": '35.5',
                            "booktypeid": '3',
                            "bookdesc": '为闺阁立传',
                            "isborrowed": '0',
                            "bookimg": 'http://wangpeng-imgsubmit.oss-cn-hangzhou.aliyuncs.com/img/202111131322401.jpg'
                        });
                        $("#demo1").attr("src", "http://wangpeng-imgsubmit.oss-cn-hangzhou.aliyuncs.com/img/202111131322401.jpg");
                    },
                    yes: function(index,layero){ //确认的回调
                        layer.close(index); //关闭弹出框
                        var mdata = form.val('editForm');
                        //向服务器请求
                        $.getJSON({
                            url: '../bookInfo/addBookInfo',
                            data: {json:JSON.stringify(mdata)},    //发json
                            success:function (res) {
                                layer.msg("添加"+res+"行成功！",{time:800});
                                //获得最后一页的页码并重载
                                $.getJSON({
                                    url: '../bookInfo/getCount',
                                    success: function (res) {
                                        //数据长度
                                        var len = res;
                                        //每页大小
                                        var size = $('.layui-laypage-limits').find('select').val();
                                        //页码: 上取整（len/size）
                                        var pageNum = Math.ceil(len / size);
                                        //重载页面
                                        table.reload('currentTableId',{page : {curr : pageNum}});
                                    }
                                });
                            }
                        });
                    }
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                layer.confirm('确定要删除选中行吗？', function(index){
                    var checkStatus = table.checkStatus('currentTableId')
                        , data = checkStatus.data;
                    layer.close(index); //关闭提示框
                    //向服务器请求
                    $.getJSON({
                        url: '../bookInfo/deleteBookInfos',
                        data: {json:JSON.stringify(data)},   //发json过去
                        success:function (res) {
                            layer.msg("删除"+res+"行成功！",{time:800});
                            //重载表格
                            table.reload('currentTableId',{page:{curr:1}});
                        }
                    });
                });
            }
        });

        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') { //监听编辑按钮
                var index = layer.open({
                    title: '编辑用户',
                    type: 1,    //界面层
                    maxmin:true,
                    shadeClose: true,
                    area: ['800px', '600px'],
                    btn: ['确定', '取消'],
                    content: $("#edit_window"),
                    success: function () {
                        var mdata = obj.data;   //获取该行的数据
                        //给表单赋值
                        form.val("editForm", {
                            "bookid": mdata.bookid,
                            "bookname": mdata.bookname,
                            "bookauthor": mdata.bookauthor,
                            "bookprice": mdata.bookprice,
                            "booktypeid": mdata.booktypeid,
                            "bookdesc": mdata.bookdesc,
                            "isborrowed": mdata.isborrowed,
                            "bookimg": mdata.bookimg
                        });
                        $("#demo1").attr("src", mdata.bookimg);
                    },
                    yes: function () {  //确认回调
                        layer.close(index); //关闭弹出框
                        var mdata = form.val('editForm');   //获取表单的数据
                        $.getJSON({
                            url: '../bookInfo/updateBookInfo',
                            data: {json:JSON.stringify(mdata)},   //发json过去
                            success:function (res) {
                                layer.msg("修改"+res+"行成功!",{time:800});
                                //重载表格
                                table.reload('currentTableId');
                            }
                        });
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {    //监听删除按钮
                layer.confirm('确定要删除该行吗？', function (index) {
                    var mdata = obj.data;    //获取该行的数据
                    obj.del();  //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index); //关闭窗口
                    //向服务器请求
                    $.getJSON({
                        url: '../bookInfo/deleteBookInfos',
                        data: {json:JSON.stringify(mdata)},   //发json过去
                        success:function (res) {
                            layer.msg("删除"+res+"行成功！",{time:800});
                        }
                    });
                });
            }
        });

    });
</script>

</body>
</html>